package cn.lxg.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Week;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import cn.lxg.dao.entity.Lottery;
import cn.lxg.dao.entity.SuperLottery;
import cn.lxg.dao.service.ISuperLotteryService;
import cn.lxg.rpc.LotteryRpc;
import cn.lxg.rpc.SuperLotteryRpc;
import cn.lxg.utils.RangeUtil;
import cn.lxg.utils.SuperLotteryBallUtils;
import cn.lxg.utils.SuperLotteryUtils;
import cn.lxg.vo.LotteryVo;
import cn.lxg.vo.SuperWinLotteryVo;
import cn.hutool.core.collection.CollectionUtil;
import cn.lxg.vo.WinLotteryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;


@RestController
@RequestMapping(value = "superLottery")
public class SuperLottoController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ISuperLotteryService superLotteryServiceImpl;

    @Autowired
    @Qualifier(value = "myAsync")
    private ThreadPoolTaskExecutor myAsync;

    @Autowired
    private SuperLotteryBallUtils superLotteryBallUtils;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //
    @GetMapping("/get")
    private void test() throws IOException {
        System.out.println("开始采集");
        int a = 1;
        while (true) {
            String url = "https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&pageSize=9999&isVerify=1&pageNo=" + a;
            Connection conn = Jsoup.connect(url);
            Document doc = conn.followRedirects(true).get();//to follow redirects
            String str = doc.body().html();
            if (StringUtils.isBlank(str)) {
                return;
            }
            JSONArray jsonArray = JSONUtil.parseObj(str).getJSONObject("value").getJSONArray("list");
            List<SuperLotteryRpc> list = jsonArray.toList(SuperLotteryRpc.class);
            if (CollectionUtil.isEmpty(list)) {
                return;
            }
            List<SuperLottery> lotteries = new ArrayList<>();
            for (SuperLotteryRpc vo : list) {
                SuperLottery lottery = new SuperLottery();
                lottery.setCode(vo.getLotteryDrawNum());
                lottery.setDate(DateUtil.parseDate(vo.getLotterySaleEndtime()));
                lottery.setWeek(DateUtil.dayOfWeekEnum(lottery.getDate()) == Week.MONDAY ? "一" : DateUtil.dayOfWeekEnum(lottery.getDate()) == Week.WEDNESDAY ? "三" : "六");
                List<Integer> ball = Arrays.stream(vo.getLotteryDrawResult().split(" ")).collect(Collectors.toList()).stream().map(Integer::valueOf).collect(Collectors.toList());
                lottery.setRed1(ball.get(0));
                lottery.setRed2(ball.get(1));
                lottery.setRed3(ball.get(2));
                lottery.setRed4(ball.get(3));
                lottery.setRed5(ball.get(4));
                lottery.setBlue1(ball.get(5));
                lottery.setBlue2(ball.get(6));
                lottery.setTotal(lottery.getRed1() + lottery.getRed2() + lottery.getRed3() + lottery.getRed4() + lottery.getRed5() + lottery.getBlue1() + lottery.getBlue2());
                lotteries.add(lottery);
            }
            //入库
            superLotteryServiceImpl.saveOrUpdateBatch(lotteries);
            a++;
        }

    }


    @GetMapping("/getData")
    private void getData() throws InterruptedException {
        LambdaQueryWrapper<SuperLottery> wrapper = new LambdaQueryWrapper<>();
        wrapper.last("order by code desc");
        //获取所有数据
        List<SuperLottery> list = superLotteryServiceImpl.list(wrapper);
        //最常出现的聚合范围 小——到大
        List<Integer> maxAndMinRange = RangeUtil.getMostFrequentNumberRange(list.stream().map(SuperLottery::getTotal).collect(Collectors.toList()));

        int queryPeriod = 300;
        int checkPeriod = 3;

        SuperWinLotteryVo result = null;
        while (true) {
            // 获取最近同周排查
            List<SuperLottery> thirtyBySameWeek = superLotteryServiceImpl.getLatelySizeBySameWeek(queryPeriod);
            //获取到前30个后 查询出 出现最多的数字
            Set<Integer> redCannotAppearNum = SuperLotteryUtils.getCannotAppearNum(superLotteryServiceImpl.getAllRedSet(thirtyBySameWeek), thirtyBySameWeek, checkPeriod, 0);
            //获取所有蓝色 查询出 出现最多的数字
            Set<Integer> blueCannotAppearNum = SuperLotteryUtils.getCannotAppearNum(superLotteryServiceImpl.getAllBlueSet(thirtyBySameWeek), thirtyBySameWeek, checkPeriod, 1);

            //获取同天排查
            List<SuperLottery> thirtyBySameDay = superLotteryServiceImpl.getLatelySizeBySameDay(queryPeriod);
            //红色
            redCannotAppearNum.addAll(SuperLotteryUtils.getCannotAppearNum(superLotteryServiceImpl.getAllRedSet(thirtyBySameDay), thirtyBySameDay, checkPeriod, 0));
            //获取所有蓝色 查询出 出现最多的数字
            blueCannotAppearNum.addAll(SuperLotteryUtils.getCannotAppearNum(superLotteryServiceImpl.getAllBlueSet(thirtyBySameDay), thirtyBySameDay, checkPeriod, 1));


            //获取同期排查
            List<SuperLottery> thirtyBySamePeriod = superLotteryServiceImpl.getLatelySizeBySamePeriod(queryPeriod);
            //红色
            redCannotAppearNum.addAll(SuperLotteryUtils.getCannotAppearNum(superLotteryServiceImpl.getAllRedSet(thirtyBySamePeriod), thirtyBySamePeriod, checkPeriod, 0));
            //获取所有蓝色 查询出 出现最多的数字
            blueCannotAppearNum.addAll(SuperLotteryUtils.getCannotAppearNum(superLotteryServiceImpl.getAllBlueSet(thirtyBySamePeriod), thirtyBySamePeriod, checkPeriod, 1));

            //直接获取最近排查
            List<SuperLottery> thirtyByDay = superLotteryServiceImpl.getLatelySizeByDay(queryPeriod);
            //红色
            redCannotAppearNum.addAll(SuperLotteryUtils.getCannotAppearNum(superLotteryServiceImpl.getAllRedSet(thirtyByDay), thirtyByDay, checkPeriod, 0));
            //获取所有蓝色 查询出 出现最多的数字
            blueCannotAppearNum.addAll(SuperLotteryUtils.getCannotAppearNum(superLotteryServiceImpl.getAllBlueSet(thirtyByDay), thirtyByDay, checkPeriod, 1));

            List<SuperWinLotteryVo> historyWin = new ArrayList<>();
            for (SuperLottery lottery : list) {
                SuperWinLotteryVo winLotteryVo = new SuperWinLotteryVo();
                List<Integer> redBall = new ArrayList<>();
                redBall.add(lottery.getRed1());
                redBall.add(lottery.getRed2());
                redBall.add(lottery.getRed3());
                redBall.add(lottery.getRed4());
                redBall.add(lottery.getRed5());
                winLotteryVo.setRedBall(redBall);

                List<Integer> blueBall = new ArrayList<>();
                blueBall.add(lottery.getBlue1());
                blueBall.add(lottery.getBlue2());
                winLotteryVo.setBlueBall(blueBall);
                winLotteryVo.setCode(lottery.getCode());
                historyWin.add(winLotteryVo);
            }

            result = superLotteryBallUtils.getWinLottery(redCannotAppearNum, blueCannotAppearNum, maxAndMinRange, historyWin);
            if (result != null) {
                break;
            }
        }

        redisTemplate.unlink(Objects.requireNonNull(redisTemplate.keys("SuperLottery*")));
        System.out.println(result);
    }


}
